import React, { useEffect, useRef, useState } from 'react'
import QuestionCard from '../../components/QuestionCard'
import { useDebounceFn, useRequest, useTitle } from 'ahooks'
import { Typography, Spin, Empty } from 'antd'
import ListSearch from '../../components/ListSearch'

import styles from './common.module.scss'
import { useSearchParams } from 'react-router-dom'
import { LIST_PAGE_SIZE, LIST_SEARCH_PARAM_KEY } from '../../constant/index'
import { getQuestionListService } from '../../services/question'

const { Title } = Typography

const List: React.FC = () => {
  useTitle('小慕问卷 - 我的问卷')

  const [searchParams] = useSearchParams()
  const [started, setStarted] = useState(false)
  const [page, setPage] = useState(1)
  const [list, setList] = useState([]) // 累计数据
  const [total, setTotal] = useState(0)
  const haveMoreData = total > list.length // 有没有更多的加载问完成的数据
  const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''

  // keyword  变化时,重置信息
  useEffect(() => {
    setStarted(false)
    setPage(1)
    setList([])
    setTotal(0)
  }, [keyword])

  // 真正加载
  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      })

      return data
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: l = [], total = 0 } = result
        setList(list.concat(l))
        setTotal(total)
        setPage(page + 1)
      },
    }
  )

  // 尝试加载的函数, 防抖
  const containerRef = useRef<HTMLDivElement>(null)
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = containerRef.current
      if (!elem) return

      const domReact = elem.getBoundingClientRect()
      if (!domReact) return
      const { bottom } = domReact

      if (bottom <= document.body.clientHeight) {
        load()
        setStarted(true)
      }
    },
    { wait: 1000 }
  )

  // 当页面加载,或者 url 参数(keyword)变化时, 触发加载
  useEffect(() => {
    tryLoadMore()
  }, [searchParams])

  //
  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener('scroll', tryLoadMore)
    }

    return () => {
      window.removeEventListener('scroll', tryLoadMore)
    }
  }, [searchParams, haveMoreData])

  const LoadMoreContentElem = () => {
    if (!started || loading) {
      return <Spin />
    }
    if (total === 0) {
      return <Empty description="暂无数据" />
    }
    if (!haveMoreData) {
      return <span>没有更多了</span>
    }

    return <span>开始加载下一页</span>
  }

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.content}>
        {list.map((q: any) => {
          const { _id } = q
          return <QuestionCard key={_id} {...q} />
        })}
      </div>
      <div className={styles.footer}>
        <div ref={containerRef}>
          <LoadMoreContentElem />
          {/* {LoadMoreContentElem()} */}
        </div>
      </div>
    </>
  )
}

export default List
